package cn.tedu._03vehicle.base.filters;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("初始化...");
    }

    /**
     * 过滤器的核心方法;
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.debug("进入登录状态校验的过滤器...");
        //实现登录状态的校验
        //1.类型转换:HttpServletRequest和ServletRequest是父子关系
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        //2.获取会话
        HttpSession session = request1.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO != null){ //登录状态
            //有此行代码,代表放行;
            //无此行代码,代表拦截;
            chain.doFilter(request1, response1);
        }else{ //未登录状态
            response1.sendRedirect("/login.html");
        }
    }

    @Override
    public void destroy() {
        log.debug("销毁...");
    }
}
